package commons.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.commons.annotation.RequirePerms;
import com.woniuxy.commons.enums.ResultEnum;
import com.woniuxy.commons.service.AuthService;
import com.woniuxy.commons.util.JwtUtil;
import com.woniuxy.commons.util.ResponseResult;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@Component
public class PermsInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private AuthService authService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断请求的是否是是controller中的方法
        if(handler instanceof HandlerMethod){
            HandlerMethod handler1 = (HandlerMethod) handler;
            Method method = handler1.getMethod();
            if(method.isAnnotationPresent(RequirePerms.class)){
                //获取方法上注解 值
                RequirePerms requirePerms = method.getDeclaredAnnotation(RequirePerms.class);
                String perms = requirePerms.value();
                //得到token
                String token = request.getHeader("authorization");
                //得到account
                String account = JwtUtil.getUname(token);
                //调用auth微服务鉴权方法：传参account、perms
                ResponseResult responseResult = authService.existPerms(account, perms);
                if(responseResult.getStatus()== ResultEnum.PERMS_YES){
                    return true;
                }
                //返回json数据告知没权限
                response.setContentType("application/json:charset=utf-8");
                String json = new ObjectMapper().writeValueAsString(responseResult);
                response.getWriter().write(json);
                return false;
            }
        }


        return false;
    }
}
